package com.system.Service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.common.Constant.Constants;
import com.common.Exception.BassException;
import com.common.Utils.JwtUtil;
import com.common.Utils.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.Entity.LoginContext;
import com.system.Entity.Register;
import com.system.Entity.Role;
import com.system.Entity.User;
import com.system.Mapper.UserMapper;
import com.system.Service.UserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String register(Register registry) throws ParseException {
        // 1.验证注册必要信息是否已存在
        String checkResult=checkUserExists(registry);
        if (checkResult.equals("User_Have")){
            return checkResult;
        }else if(checkResult.equals("Email_Have")){
            return checkResult;
        }else if(checkResult.equals("Phone_Have")){
            return checkResult;
        }
        // 2. 对密码进行加密
        String encryptedPassword = MD5Util.encrypt(registry.getPassword());
        // 3. 设置加密后的密码
        registry.setPassword(encryptedPassword);
        // 4. 创建用户实体并设置信息
        User user = new User();
        // 5.生成用户ID (当前时间戳 + 4位随机数)
        user.setUserId(generateUserId());
        // 6.设置基本信息
        user.setUserName(registry.getUsername());
        user.setPassword(encryptedPassword);
        user.setEmail(registry.getEmail());
        user.setPhone(registry.getPhone());

        // 7.设置默认昵称（用户名+随机4位数）
        String screenName = "JingJu" + "_" + String.format("%04d", new Random().nextInt(10000));
        user.setScreenName(screenName);
        // 设置默认头像(从阿里云oss存储对象随机获取默认头像)
        String avatar = getRandomAvatar();
        user.setAvatar(avatar);
        // 设置用户状态
        user.setStatus(Constants.USER_STATUS_NORMAL);

        // 设置用户类型
        user.setRoleId(Constants.USER_TYPE_NORMALUSER);


        // 设置注册时间

//        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = formatter.parse(getChinaTime());
        user.setRegisterTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));

        // 设置默认签名
        user.setDescription(Constants.USER_SIGNATURE);
        // 8.信息添加到数据库
        userMapper.InsertUserMsg(user);

        userMapper.insertUser_Role(user.getUserId());

        return "ok";
    }

    @Override
    public String Accountlogin(LoginContext loginContext) {

        // 验证用户凭据（这里可以调用数据库查询用户）
        String username = loginContext.getUsername();
        String password = loginContext.getPassword();
        //二次加密 对比数据库结果
        String encryptedPassword = MD5Util.encrypt(password);

        User usernameResult = userMapper.SerachUsername(username);
        if (usernameResult==null){
            return "UserError_N";
        }
        if (Objects.equals(usernameResult.getStatus(), Constants.USER_STATUS_NORMAL)) {
            if (usernameResult.getPassword().equals(encryptedPassword)) {

                userMapper.updateLoginTime(String.valueOf(LocalDateTime.now(ZoneId.of("Asia/Shanghai"))),username);
                // 生成JWT
                String token = JwtUtil.generateToken(username);
                // 将token存储到Redis，设置过期时间
                redisTemplate.opsForValue().set(username, token, 3600, TimeUnit.SECONDS);
                return token;
            } else {
                return "pwdError";
//                throw new BassException(Constants.PASSWORD_ERROR);
            }
        } else if (usernameResult.getStatus().equals(Constants.USER_STATUS_DISABLE)) {
            return "UserError_D";
//            throw new BassException(Constants.USER_STATUS_DISABLE_ERROR);
        }
        return "false";
    }
    /**
     * 手机号登陆
     */
    @Override
    public String Phonelogin(LoginContext loginContext) {
        String phone = loginContext.getPhone();
        User userResult = userMapper.SerachPhone(phone);
        String username = userResult.getUserName();
        if (userResult.getStatus().equals(Constants.USER_STATUS_NORMAL)) {

            userMapper.updateLoginTime(String.valueOf(LocalDateTime.now(ZoneId.of("Asia/Shanghai"))),username);
            // 生成JWT
            String token = JwtUtil.generateToken(username);
            // 将token存储到Redis，设置过期时间
            redisTemplate.opsForValue().set(username, token, 3600, TimeUnit.SECONDS);
            return token;
        } else if (userResult.getStatus().equals(Constants.USER_STATUS_DISABLE)) {
            return "UserError_D";
        }

        return "false";
    }
    /**
     * 邮箱登录
     */
    @Override
    public String Emaillogin(LoginContext loginContext) {
        String email = loginContext.getEmail();
        User userResult = userMapper.SerachEmail(email);
        String username = userResult.getUserName();
        if (userResult.getStatus().equals(Constants.USER_STATUS_NORMAL)) {

            userMapper.updateLoginTime(String.valueOf(LocalDateTime.now(ZoneId.of("Asia/Shanghai"))),username);
            // 生成JWT
            String token = JwtUtil.generateToken(username);
            // 将token存储到Redis，设置过期时间
            redisTemplate.opsForValue().set(username, token, 3600, TimeUnit.SECONDS);
            return token;
        } else if (userResult.getStatus().equals(Constants.USER_STATUS_DISABLE)) {
            return "UserError_D";
        }
        return "false";
    }
    /**
     * 更改头像
     */
    @Override
    public void updateUserAvatar(String username, String avatarUrl) {
        //修改头像
        userMapper.updateAvatarByUserName(username,avatarUrl);
    }

    @Override
    public void updateUserProfile(User user)  {
//        LocalDateTime dateTime = LocalDateTime.now();
        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        user.setUpdateUser(user.getUserName());
        userMapper.updateUserProfile(user);

    }

    @Override
    public boolean changePassword(String username, String oldPWD, String newPWD) {

            String encryptedOldPWD = MD5Util.encrypt(oldPWD);
            String encryptedNewPWD = MD5Util.encrypt(newPWD);
            User user = userMapper.SerachUsername(username);
            if (Objects.equals(user.getPassword(), encryptedOldPWD)) {
                userMapper.updatePassword(username,encryptedNewPWD);
                return true;
            }

        return false;
    }

    @Override
    public void changePassword_Login(String userName, String newPWD) {
        userMapper.updatePassword(userName,MD5Util.encrypt(newPWD));
    }

    @Override
    public PageInfo<User> getUserList(Integer pageNum, Integer pageSize, String userName) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.getUserList(userName);
        return new PageInfo<>(userList);
    }

    @Override
    public PageInfo<Role> getRoleList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Role> roleList = userMapper.getRoleList();
        return new PageInfo<>(roleList);

    }

    @Override
    public String addUser(User user) throws ParseException {
        // 1.验证必要信息是否已存在
        Integer usernameResult = userMapper.funUsername(user.getUserName());
        if (usernameResult > 0) {
            return "User_Have";
        }
        // 2. 对密码进行加密
        String encryptedPassword = MD5Util.encrypt(user.getPassword());
        // 3.生成用户ID (当前时间戳 + 4位随机数)
        user.setUserId(generateUserId());
        // 4..设置基本信息
//        user.setUserName(user.getScreenName());
        user.setPassword(encryptedPassword);
//        user.setEmail(user.getEmail());
//        user.setPhone(registry.getPhone());

        // 7.设置默认昵称（用户名+随机4位数）
        String screenName = "JingJu" + "_" + String.format("%04d", new Random().nextInt(10000));
        user.setScreenName(screenName);
        // 设置默认头像(从阿里云oss存储对象随机获取默认头像)
        String avatar = getRandomAvatar();
        user.setAvatar(avatar);
//        // 设置用户状态
//        user.setStatus(Constants.USER_STATUS_NORMAL);

//        // 设置用户类型
//        user.setRoleId(Constants.USER_TYPE_NORMALUSER);

        // 设置注册时间

        user.setRegisterTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));

        // 设置默认签名
        user.setDescription(Constants.USER_SIGNATURE);
        // 信息添加到数据库
        userMapper.InsertUserMsg(user);

        userMapper.insertUser_Role_A(user.getUserId(),user.getRoleId());

        return "ok";


    }

    @Override
    public void updateUser_A(User user) {

        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));

        userMapper.updateUser_A_status(user.getUserId(),user.getStatus(),user.getUpdateUser(),user.getUpdateTime());
        userMapper.updateUser_A_role(user.getUserId(),user.getRoleId(),user.getUpdateUser(),user.getUpdateTime());
    }

    @Override
    public User getUserByName(String userName) {
        return  userMapper.SerachUsername(userName);
    }

    /**
     * 生成用户ID
     */
    private String generateUserId() {
        // 时间戳 + 4位随机数
        String timestamp = String.valueOf(System.currentTimeMillis());
        String random = String.format("%04d", new Random().nextInt(10000));
        return "U" + timestamp + random;
    }


    /**
     * 检查是否存在相同用户名、手机号和邮箱
     */
    private String checkUserExists(Register registry) {
        String email = registry.getEmail();
        String username = registry.getUsername();
        String phone = registry.getPhone();
        Integer usernameResult = userMapper.funUsername(username);
        if (usernameResult > 0) {
           return "User_Have";
        }
        Integer emailResult = userMapper.funEmail(email);
        if (emailResult > 0) {

            return "Email_Have";

        }
        Integer phoneResult = userMapper.funPhone(phone);
        if (phoneResult > 0) {
            return "Phone_Have";
        }
        return "ok";
    }


    /**
     * 默认随机获取用户头像
     */
    public String getRandomAvatar() {
        // 头像文件列表
        List<String> avatars = new ArrayList<>();
        avatars.add("UserAvatar/Avatar1.jpg");
        avatars.add("UserAvatar/Avatar2.jpg");
        avatars.add("UserAvatar/Avatar3.jpg");
        avatars.add("UserAvatar/Avatar4.jpg");

        // 随机选择一个头像
        Random random = new Random();
        String selectedAvatar = avatars.get(random.nextInt(avatars.size()));

        // 生成头像的URL
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String avatarUrl = "https://" + bucketName + "." + endpoint + "/" + selectedAvatar;

        // 关闭OSS客户端
        ossClient.shutdown();

        return avatarUrl;
    }

//    public String getChinaTime() {
//        ZonedDateTime beijingTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
//        // 格式化时间
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//        return beijingTime.format(formatter);
//    }





}
